<?php

namespace app\admin\library\traits;

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use Throwable;
use ba\Filesystem;
use think\exception\HttpResponseException;
use think\facade\Db;

/**
 * 后台控制器trait类
 * 已导入到 @see \app\common\controller\Backend 中
 * 若需修改此类方法：请复制方法至对应控制器后进行重写
 */
trait Backend
{
    private function getExportColumnName(){
        return ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ',
            'BA','BB','BC','BD','BE','BF','BF','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ'];
    }
    public function export(): void{
        set_time_limit(0);// 脚本执行时间限制
        ini_set('memory_limit', 1024 . 'M');// 脚本内存限制
        try {
            if(method_exists($this,'getExportData')){
                $data = $this->getExportData();
            }else{
                list($where, $alias, $limit, $order) = $this->queryBuilder();

                $where = $this->getWhere($where);
                $data = $this->model
                    ->field($this->indexField)
                    ->withJoin($this->withJoinTable, $this->withJoinType)
                    ->alias($alias)
                    ->where($where)
                    ->order($order)
                    ->select()->toArray();
            }
            if(!$data) $this->error('无数据可导出');
            $spreadsheet = new Spreadsheet();
            $worksheet   = $spreadsheet->getActiveSheet();

            $taskName = $this->setExportTitle();
            $worksheet->setTitle($taskName);
            $head = $this->setExportHead();
            $culumnName = $this->getExportColumnName();
            $headcount = count($head);
            for ($i = 0; $i < $headcount; $i++){
                $worksheet->setCellValue([$i+1, 1], $head[$i]);
                $worksheet->getColumnDimension($culumnName[$i])->setAutoSize(true);
            }
            $this->setExportData($data,$worksheet);
            ob_end_clean();
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
            header("Content-Type:application/force-download");
            header("Content-Type:application/vnd.ms-execl");
            header("Content-Type:application/octet-stream");
            header("Content-Type:application/download");
            $taskName        =  $taskName . '.xls';
            $encodedFilename = urlencode($taskName);
            $ua              = $_SERVER["HTTP_USER_AGENT"];
            if (str_contains($ua, "MSIE")) {
                header('Content-Disposition: attachment; filename="' . $encodedFilename . '"');
            } else if (str_contains($ua, "Firefox")) {
                header('Content-Disposition: attachment; filename*="utf8\'\'' . $taskName . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $taskName . '"');
            }
            header("Content-Transfer-Encoding:binary");
            header('Cache-Control: max-age=0');
            $writer = new Xls($spreadsheet);
            $writer->save('php://output');
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);


        }catch (\Exception $e){
            dd($e);
            $this->error('导出失败',$e->getMessage());
        }

    }
    protected function getExportResult($file){
        return request()->host().$file;
    }

    /**
     * 设置导出数据
     * @param $data
     * @param $worksheet
     * @return void
     */
    protected function setExportData($data,&$worksheet){

        foreach ($data as $key => $item){
            $row = $key + 2;
            $k = 0;
            foreach ($item as $value){
                $k += 1;
                $worksheet->setCellValue([$k, $row],$value);
            }
        }
    }
    /**
     * 导出表头
     * @return array
     */
    protected function setExportHead(): array
    {
        $table = $this->model->getName();
        $fieldList = get_table_fields(strtolower($table));
        $dataTypeInt = [
            'tinyint',
            'int',
            'smallint',
            'mediumint',
            'integer',
            'bigint'
        ];
        $fields = [];
        foreach ($fieldList as $key => $item) {
            $discern = 'text'; // 文本
            if (in_array($item['DATA_TYPE'], $dataTypeInt)) {
                $discern = 'int'; // 数字
            }
            if (preg_match("/time$|datetime$/i", $key)) {
                $discern = 'time'; // 日期时间
            }
            if (preg_match("/switch$|toggle$/i", $key)) {
                $discern    = 'valuation';// 赋值
                $commentVal = '0=关闭,1=开启';
            }

            $comment = str_replace('，', ',', $item['COLUMN_COMMENT']);
            $comment = str_replace(['(多选)', '(单选)', '（多选）', '（单选）'], '', $comment);
            if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
                list($fieldName, $commentVal) = explode(':', $comment);
                $discern = 'valuation';// 赋值
            }

            $fields[$key] = [
                'name'    => $key,
                'discern' => $discern,
                'title'   => $fieldName ?? ($item['COLUMN_COMMENT'] ? $item['COLUMN_COMMENT'] : $key),
                'comment' => $commentVal ?? '',
            ];
            unset($commentVal, $fieldName);
        }
        return array_column($fields,'title');
    }

    /**
     * 导出标题
     * @return string
     */
    protected function setExportTitle(): string
    {
        $tablePrefix     = config('database.connections.mysql.prefix');
        $list = get_table_list();
        $name = $tablePrefix.strtolower($this->model->getName());
        $title = !empty($list[$name]) ? explode(' - ',$list[$name])[1] : $name;
        return $title . '_' . date('YmdHis', time());
    }

    /**
     * 导出 获取其他查询条件
     * @param array $where
     * @return array
     */
    protected function getWhere(array $where): array
    {
        return $where;
    }

    /**
     * 导入数据 必须在控制器中定义 saveImport 方法保存数据
     * @return void
     */
    public function import()
    {
        set_time_limit(0);
        $file  = $this->request->request('file_path', '');
        // $file = str_replace(env('app.APP_URL'), '', $file);


        $filePath    = Filesystem::fsFit(public_path() . $file);

        $spreadsheet = IOFactory::load($filePath);

        $sheet       = $spreadsheet->getSheet(0);
        //获取导入的图片，这个项目暂时没有图片，先注释
        // $image_data = $this->getImportImages($spreadsheet);
        $image_data = [];
        // 表格全部数据
        $data        = $sheet->toArray();
        // 第一行是标题，所以要去掉，这个项目导入需要表头
        // unset($data[0]);
        $data = array_values($data);
        if(!$data) $this->error('无数据');
        Db::startTrans();
        try {
            //控制中实现写入数据库
            $res = $this->saveImport($data,$image_data);
            Db::commit();
            unlink($filePath);
        }catch (Throwable $e){
            Db::rollback();
            unlink($filePath);
            if($e  instanceof  HttpResponseException){
                throw $e;
            }
            $this->error($e->getMessage());
        }
        if($res === false){
            $this->error('导入失败');
        }
        $this->success('导入成功');
    }
    protected function getImportImages($spreadsheet){
        $importImages = [];
        $worksheet = $spreadsheet->getActiveSheet();
        $savePath = '/storage/uploads/'.date('Ymd').'/';
        if(!is_dir(public_path().$savePath)){
            mkdir(public_path().$savePath,0777,true);
        }
        $all = $worksheet->getDrawingCollection();
        foreach ($all as $drawing){
            if($drawing instanceof MemoryDrawing){
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $filename = 'memory_image_' . uniqid() . '.png';
                $this->saveMemoryDrawing($drawing, public_path().$savePath.$filename);
                $image_url = env('app.APP_URL'). $savePath . $filename;
                $importImages[] = [
                    //图片位置 行
                    'row' => $startRow - 2,
                    //图片位置 列
                    'column' => Coordinate::columnIndexFromString($startColumn) - 1,
                    'image' => $image_url,
                ];
            }
        }
        return $importImages;
    }
    protected function saveMemoryDrawing(MemoryDrawing $drawing, $path) {
        ob_start();
        call_user_func($drawing->getRenderingFunction(), $drawing->getImageResource());
        $imageData = ob_get_clean();
        file_put_contents($path, $imageData);
    }
    /**
     * 排除入库字段
     * @param array $params
     * @return array
     */
    protected function excludeFields(array $params): array
    {
        if (!is_array($this->preExcludeFields)) {
            $this->preExcludeFields = explode(',', (string)$this->preExcludeFields);
        }

        foreach ($this->preExcludeFields as $field) {
            if (array_key_exists($field, $params)) {
                unset($params[$field]);
            }
        }
        return $params;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 删除
     * @throws Throwable
     */
    public function del(): void
    {
        $where             = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $ids     = $this->request->param('ids/a', []);
        $where[] = [$this->model->getPk(), 'in', $ids];
        $data    = $this->model->where($where)->select();

        $count = 0;
        $this->model->startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 排序 - 增量重排法
     * @throws Throwable
     */
    public function sortable(): void
    {
        $pk        = $this->model->getPk();
        $move      = $this->request->param('move');
        $target    = $this->request->param('target');
        $order     = $this->request->param("order/s") ?: $this->defaultSortField;
        $direction = $this->request->param('direction');

        $dataLimitWhere    = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $dataLimitWhere[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $moveRow   = $this->model->where($dataLimitWhere)->find($move);
        $targetRow = $this->model->where($dataLimitWhere)->find($target);

        if ($move == $target || !$moveRow || !$targetRow || !$direction) {
            $this->error(__('Record not found'));
        }

        // 当前是否以权重字段排序（只检查当前排序和默认排序字段，不检查有序保证字段）
        if ($order && is_string($order)) {
            $order = explode(',', $order);
            $order = [$order[0] => $order[1] ?? 'asc'];
        }
        if (!array_key_exists($this->weighField, $order)) {
            $this->error(__('Please use the %s field to sort before operating', [$this->weighField]));
        }

        // 开始增量重排
        $order = $this->queryOrderBuilder();
        $weigh = $targetRow[$this->weighField];

        // 波及行的权重值向上增加还是向下减少
        if ($order[$this->weighField] == 'desc') {
            $updateMethod = $direction == 'up' ? 'dec' : 'inc';
        } else {
            $updateMethod = $direction == 'up' ? 'inc' : 'dec';
        }

        // 与目标行权重相同的行
        $weighRowIds    = $this->model
            ->where($dataLimitWhere)
            ->where($this->weighField, $weigh)
            ->order($order)
            ->column($pk);
        $weighRowsCount = count($weighRowIds);

        // 单个 SQL 查询中完成大于目标权重行的修改
        $this->model->where($dataLimitWhere)
            ->where($this->weighField, $updateMethod == 'dec' ? '<' : '>', $weigh)
            ->whereNotIn($pk, [$moveRow->$pk])
            ->$updateMethod($this->weighField, $weighRowsCount)
            ->save();

        // 遍历与目标行权重相同的行，每出现一行权重值将额外 +1，保证权重相同行的顺序位置不变
        if ($direction == 'down') {
            $weighRowIds = array_reverse($weighRowIds);
        }

        $moveComplete = 0;
        $weighRowIds  = implode(',', $weighRowIds);
        $weighRows    = $this->model->where($dataLimitWhere)
            ->where($pk, 'in', $weighRowIds)
            ->orderRaw("field($pk,$weighRowIds)")
            ->select();

        // 权重相等行
        foreach ($weighRows as $key => $weighRow) {
            // 跳过当前拖动行（相等权重数据之间的拖动时，被拖动行会出现在 $weighRows 内）
            if ($moveRow[$pk] == $weighRow[$pk]) {
                continue;
            }

            if ($updateMethod == 'dec') {
                $rowWeighVal = $weighRow[$this->weighField] - $key;
            } else {
                $rowWeighVal = $weighRow[$this->weighField] + $key;
            }

            // 找到了目标行
            if ($weighRow[$pk] == $targetRow[$pk]) {
                $moveComplete               = 1;
                $moveRow[$this->weighField] = $rowWeighVal;
                $moveRow->save();
            }

            $rowWeighVal                 = $updateMethod == 'dec' ? $rowWeighVal - $moveComplete : $rowWeighVal + $moveComplete;
            $weighRow[$this->weighField] = $rowWeighVal;
            $weighRow->save();
        }

        $this->success();
    }

    /**
     * 加载为select(远程下拉选择框)数据，默认还是走$this->index()方法
     * 必要时请在对应控制器类中重写
     */
    public function select(): void
    {

    }
}